import { baseURL } from './env.js';
import { envType } from './env.js';
import Vue from 'vue'
function isWeChat() {
	let ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		let system = {
			win: false,
			mac: false
		};
		//检测平台
		let p = navigator.platform;
		system.win = p.indexOf("Win") == 0;
		system.mac = p.indexOf("Mac") == 0;
		if (system.win || system.mac) {
			return false
		} else {
			return true
		}
	}else{
		return false
	}
}

// 判断是否是微信环境
function isWeiXin() {
	let ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_') {
		return true;
	} else {
		return false;
	}
}

// 上传视频
function chooseVideo(url) {
	return new Promise((resove, reject) => {
		uni.chooseVideo({
			sourceType: ['album', 'camera'],
			compressed: false,
			success: res => {
				uni.showLoading({
					title: '上传视频中...'
				})
				let type = 'video'
				let format = res.name.split('.')[1]
				if (format.toLowerCase() !== 'mp4') {
					type = 'mov'
				}
				uni.uploadFile({
					url,
					fileType: 'video',
					filePath: res.tempFilePath.toLowerCase(),
					name: 'file',
					formData: {
						token: token,
						type
					},
					success: res1 => {
						console.log(res1, '58')
						if (res1.statusCode !== 200) {
							uni.hideLoading()
							return uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
						resove(res1)
						uni.hideLoading()
					},
					fail: err1 => {}
				})
			},
			fail: err => {
				reject(err)
			}
		})
	})
}


// 上传图片
function chooseImg(count = 1) {
	
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			// sizeType: ['compressed'],
			sizeType: ['original', 'compressed'],
			success: res => {
				
				uni.showLoading({
					title: '上传中...'
				})
				const tempFilePathArr = res.tempFilePaths;
				let pathArr = []
				tempFilePathArr.forEach(pathItem => {
					uploadFile(pathItem).then(res3 => {
						let res4 = JSON.parse(res3)
						res4.imageData = pathItem
						pathArr.push(res4)
						if (pathArr.length == tempFilePathArr.length) {
							uni.hideLoading()
							resolve(pathArr)
						}
					}).catch(err => {
						uni.hideLoading()
						reject(err)
					})
				})
			},
			fail: err => {
				uni.hideLoading()
				reject(err)
			}
		})
	}).catch(error => {
		console.error(error)
	})
}


function uplodeFile(count = 1){
	
	return new Promise((resolve, reject) => {
		wx.chooseMessageFile({
			type:'file',
			count,
			success: res => {
				uni.showLoading({
					title: '上传中...'
				})
                
				const tempFilePathArr = res.tempFiles;
				let pathArr = []
				tempFilePathArr.forEach(pathItem => {
					uploadFile(pathItem.path,1).then(res3 => {
						let res4 = JSON.parse(res3)
						res4.imageData = pathItem
						resolve(res4)
						uni.hideLoading()
					}).catch(err => {
						uni.hideLoading()
						reject(err)
					})
				})
			},
			fail: err => {
				console.log(err)
				uni.hideLoading()
				reject(err)
			}
		})
	}).catch(error => {
		console.error(error)
	})
}



// 图片上传服务器
function uploadFile(path) {
	let url
	if(envType=='dev'){
		 url =  baseURL + '/uplodeFile/uplodeImageLocalH5'
	}else{
		url =  baseURL + '/uplodeFile/uplodeImageH5'
	}
	
	
	let token = uni.getStorageSync('token')
	let mid = uni.getStorageSync('mid')
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url,
			filePath: path.toLowerCase(),
			name: 'file',
			formData: {
				token: token,
				mid:mid
			},
			success: (res1) => {
				const result = res1.data
				resolve(result)
			},
			fail: (err) => {
				reject(err)
			}
		})
	}).catch(err => {
		console.error(err)
	})
}

function downloadFile(url,filetype){
	
	
		uni.downloadFile({
			url,url,
			success: data => {
				let filePath = data.tempFilePath
				const typeObj = {
					gif: 'img',
					GIF: 'img',
					png: 'img',
					PNG: 'img',
					jpg: 'img',
					JPG: 'img',
					jpeg: 'img',
					mp4: 'video',
					doc: 'doc',
					docx: 'doc',
					xls: 'doc',
					xlsx: 'doc',
					ppt: 'doc',
					pptx: 'doc',
					pdf: 'doc'
				},	
				result = (ok = '成功保存到相册', no = '保存失败') => {
					return {
						filePath,
						success: res => {
							uni.showToast({
								title: ok
							})
						},
						fail: err => {
							uni.showToast({
								title: no
							})
						}
					}
				}
				
				if (typeObj[filetype] === 'video') {
					// 保存视频到系统相册:mp4
					uni.saveVideoToPhotosAlbum(result())
				} else if (typeObj[filetype] === 'img') {
					// 保存图片到系统相册:gif,jpg,jpeg,png,GIF,JPG,PNG
					uni.saveImageToPhotosAlbum(result())
				} else {
					// 打开文件:doc,docx,xls,xlsx,ppt,pptx,pdf
					uni.openDocument({
						...result('打开文档成功', '打开文档失败'),
						showMenu: true//showMenu是否显示右上角菜单
					});
				}
				return
				
				
				
				console.log(data.tempFilePath)
				            console.log(JSON.stringify(data))
				            if (data.statusCode === 200) {
				              uni.saveFile({ //文件保存到本地
				                tempFilePath: data.tempFilePath, //临时路径
				                success: function(res) {
									resolve(res)
				                  console.log("下载成功"+res.savedFilePath)
				                  console.log(JSON.stringify(res))
				                  uni.showToast({
				                    icon: 'none',
				                    mask: true,
				                    title: '文件已保存!', 
				                    duration: 3000,
				                  });
				                  uni.openDocument({
				                    fileType: 'doc',
				                    filePath: res.savedFilePath,
				                    success: function(res) {
				                      console.log('打开文档成功');
				                    }
				                  });
				                }
				    });
				}
			},
			fail: err => {
				console.log(err);
				uni.showToast({
				  icon: 'none',
				  mask: true,
				  title: '失败请重新下载',
				});
				reject(err)
			}
		})
	
}






function iosHeight() {
	let areaH = ''
	uni.getSystemInfo({
		success: (res) => {
			areaH = res.safeArea.height
		}
	})
	return areaH
}


function iosBottomHeight() {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: function(res) {
				console.log('352 352 352 352 352 ')
				console.log(res)
				let model = ['X', 'XR', 'XS', '11', '12', '13', '14', '15'];
				let num = 0
				model.forEach(item => {
					//适配iphoneX以上的底部，给tabbar一定高度的padding-bottom
					if (res.model.indexOf(item) != -1 && res.model.indexOf('iPhone') != -1) {
						num = 40
						uni.setStorageSync('paddingBottomHeight',40)
					}
				})
				resolve(num)
			}
		})
	})
}

export default {
	downloadFile,
	uplodeFile,
	iosBottomHeight,
	chooseImg,
	uploadFile,
	isWeiXin,
	isWeChat,
	iosHeight,
	chooseVideo
}
